import JJLog from './JJLog'
import { JJUtil } from '.';

// 存放
let __notices = [];

export default class JJNotification {

    /**
    * addNotification
    * 注册通知对象方法
    * 
    * 参数:
    * observer: 注册对象
    * selector: 对应的通知方法，接受到通知后进行的动作
    * name: 注册名，一般let在公共类中
    * anObject: 如果设置，postNotificationName中只能设置相同的anObject才能接收到
    */
    static addNotification(observer, selector, name, anObject) {
        for (let i = 0; i < __notices.length; i++) {
            const notice = __notices[i];
            if (notice.name === name && notice.observer === observer) {
                return
            }
        }

        if (name && selector) {   
            const newNotice = {
                name: name,
                selector: selector,
                observer: observer,
                anObject: anObject
            };
    
            JJNotification.__addNotices(newNotice);
        } else {
            JJLog.error('addNotification error: no selector or name')
        }
    }

    static __addNotices(newNotice) {
        __notices.push(newNotice);
    }

    static removeNotification(observer, name, anObject) {
        const deleteIndexList = []
        for (let i = 0; i < __notices.length; i++){
            const notice = __notices[i]
            if (JJUtil.isNull(name) && notice.observer === observer) {
                deleteIndexList.push(i)
            } else if (notice.name === name) {
                if (JJUtil.isNull(notice.anObject) || notice.anObject === anObject) {
                    deleteIndexList.push(i)
                }
            }
        }

        for (let j = deleteIndexList.length; j > 0; --j) {
            __notices.splice(deleteIndexList[j - 1], 1) // 从队列删除
        }
    }

    static postNotificationName(name, info, anObject) {
        if(__notices.length === 0){
            JJLog.warn("postNotificationName Warning: hadn't add any notice.");
            return;
        }
    
        for (let i = 0; i < __notices.length; i++){
          const notice = __notices[i];
          if(notice.name === name){
              if (JJUtil.isNull(notice.anObject) || notice.anObject === anObject) {
                notice.selector(info)
              }
          }
        } 
    }

    static registerNotificaitonCount() {
        return __notices.length
    }

    static removeAllNotificaiton() {
        __notices = []
    }
}
